<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">面经后台</el-breadcrumb-item>
      <el-breadcrumb-item>面经管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>共 {{ total }} 条记录</span>
        <el-button
          size="small"
          @click="add"
          style="float: right"
          type="primary"
          round
          >+ 添加面经</el-button
        >
      </div>
      <!-- 表格 -->
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column label="标题" prop="stem" width="400"></el-table-column>
        <el-table-column label="作者" prop="creator"></el-table-column>
        <el-table-column
          label="点赞"
          prop="likeCount"
          width="150"
        ></el-table-column>
        <el-table-column label="浏览数" prop="views"></el-table-column>
        <el-table-column label="更新时间" prop="createdAt"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              @click="preview(row.id)"
              type="primary"
              icon="el-icon-view"
              circle
            ></el-button>
            <el-button
              type="success"
              @click="Theeditor(row.id)"
              icon="el-icon-edit"
              circle
            ></el-button>
            <el-button
              @click="remove(row.id)"
              type="info"
              icon="el-icon-delete"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 抽屉 -->
    <el-drawer
      size="50%"
      :title="title"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <div v-if="this.title === '预览面经'" class="previw">
        <h1>{{ this.userinfo.stem }}</h1>
        <span v-html="this.userinfo.content"></span>
      </div>
      <el-form
        :model="userinfo"
        ref="reference"
        :rules="rules"
        label-width="80px"
        v-else
      >
        <el-form-item label="标题" prop="stem">
          <el-input
            v-model="userinfo.stem"
            placeholder="输入面经标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <quillEditor
            @blur="$refs.reference.validateField('content')"
            :options="editorOption"
            v-model="userinfo.content"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="qr">确认</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { ListAPI } from '@/api/user'
import { articleAPI, viewAPI, updatedAPI, deleteAPI } from '@/api/article'

import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'

// 定制 quillEditor 复本编辑器
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ['blockquote', 'code-block'], // 引用  代码块-----['blockquote', 'code-block']
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  [{ align: [] }] // 对齐方式-----[{ align: [] }]
]

export default {
  name: 'ArtiCle',
  components: {
    quillEditor
  },
  data () {
    return {
      tableData: [], // 数据
      current: 1, // 当前页
      pageSize: 10, // 分页展示多少
      total: null, // 总数量
      drawer: false, // 抽屉开关
      direction: 'rtl', // 从右往做开
      title: '', // 抽屉的标题
      userinfo: {
        stem: '', // 标题
        content: '', // 内容
        id: null
      },
      // 富文本编辑器工具
      editorOption: {
        theme: 'snow',
        modules: {
          toolbar: toolbarOptions
        }
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    this.list()
  },
  methods: {
    // 获取数据
    async list () {
      const res = await ListAPI({
        current: this.current,
        pageSize: this.pageSize
      })

      const { data } = res
      // console.log(data)

      this.tableData = data.data.rows

      this.total = data.data.total
    },
    // 每页几条
    handleSizeChange (val) {
      // console.log(val)
      this.pageSize = val
      this.current = 1
      this.list()
    },
    // 页码
    handleCurrentChange (val) {
      // console.log(val)
      this.current = val
      this.pageSize = 10
      this.list()
    },
    // 添加面经
    add () {
      this.userinfo.stem = ''
      this.userinfo.content = ''
      this.title = '添加面经'
      this.drawer = true
    },
    // 点击预览
    async preview (id) {
      this.title = '预览面经'
      this.drawer = true

      const res = await viewAPI(id)

      // console.log(res)

      this.userinfo.stem = res.data.data.stem

      this.userinfo.content = res.data.data.content
    },
    // 点击编辑
    async Theeditor (id) {
      this.title = '编辑面经'
      this.drawer = true
      // console.log(id)
      this.userinfo.id = id

      const res = await viewAPI(id)

      // console.log(res)

      this.userinfo.stem = res.data.data.stem

      this.userinfo.content = res.data.data.content
    },
    // 点击删除
    remove (id) {
      // console.log(id)

      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await deleteAPI(id)

        // console.log(res)

        this.tableData.forEach((item, index) => {
          if (item.id === id) {
            if ((this.current - 1) * this.pageSize + index + 1 === this.total && index === 0 && this.current > 1) {
              this.current += -1
            }
          }
        })
        if (res.data.code === 10000) {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success'
          })
          this.list()
        }
      })
    },
    // 关闭抽屉
    handleClose () {
      // 每次关闭都要重置表单 因为不重置内容还会校验
      if (!this.title === '预览面经') {
        this.$refs.reference.resetFields()
      }
      this.drawer = false
    },
    // 点击确认
    qr () {
      // console.log(1)
      this.$refs.reference.validate(async (valid) => {
        if (valid) {
          if (this.title === '添加面经') {
            const res = await articleAPI(this.userinfo)

            // console.log(res)

            if (res.data.code === 10000) {
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success'
              })
            }
          }
          if (this.title === '编辑面经') {
            const res = await updatedAPI(this.userinfo)

            // console.log(res)
            if (res.data.code === 10000) {
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success'
              })
            }
          }

          // 关闭抽屉
          this.handleClose()
          // 重新渲染页面
          this.list()
        }
      })
    }

  }
}

</script>

<style lang='scss' scoped>
.box-card {
  margin-top: 50px;
}
.el-pagination {
  margin-top: 20px;
  margin-left: 25%;
}
.el-form ::v-deep .el-input__inner {
  width: 90%;
}

.el-form ::v-deep .quill-editor {
  width: 90%;
}
.el-form ::v-deep .ql-container.ql-snow {
  height: 300px;
}
.previw {
  padding: 0 40px 40px 40px;
  > h1 {
    font-size: 30px;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
  }
  > span {
    font-size: 20px;
    color: #666;
  }
}
</style>
